<template>
    <div class="login-by-account">
        <el-form ref="accountFormRef" 
                  :model="accountForm" 
                  :rules="accountFormRules"
                  class="login-form"
                  label-width="0">
                <el-form-item prop="account">
                    <el-input v-model="accountForm.mobile" placeholder="请输入账户名"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="accountForm.pwd" placeholder="请输入密码" type="password"></el-input>
                </el-form-item>
        </el-form>
        <el-button  
            :disabled="!(Boolean(accountForm.mobile) && Boolean(accountForm.pwd))" 
            @click="submitForm(accountFormRef)"
            class="btn" 
            type="primary">登录</el-button>
        <div class="row">
            <el-checkbox v-model="isRemember" label="记住账号"></el-checkbox>    
            <!-- <div class="tip">
                <span class="text">还没有账号？</span>
                <span class="link" @click="register">去注册</span>
            </div> -->
        </div>            
    </div>
</template>
<script lang="ts" setup>
import {ref, reactive} from 'vue';

import type { FormInstance, FormRules } from 'element-plus'

import { login } from 'services/system'

const emits = defineEmits(['submit', 'register'])
const isRemember = ref(false)
const accountFormRef = ref<FormInstance>()
const accountForm = ref({
    mobile:'',
    pwd:''
})
const accountFormRules = reactive<FormRules>({
    mobile:[{required:true,message:'请输入账户名或手机号', trigger:'blur'}],
    pwd:[{required:true,message:'请输入密码', trigger:'blur'}]
})

let account = window.localStorage.getItem('account')
if (account) {
    isRemember.value = true;
    accountForm.value.mobile = account
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            login(accountForm.value).then((res:any) => {
                if (isRemember.value) {
                    window.localStorage.setItem('account', accountForm.value.mobile)
                } else {
                    window.localStorage.removeItem('account')
                }
                emits('submit', res.token)
            }).catch(err => {
                console.log(err, 'err')
            })
        } else {
            console.log('error submit', fields)
        }
    }) 
}

const register = () => {
    emits('register')
}

</script>
<style lang="scss">
.login-by-account{
   
    .row{
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 48px;
        width: 100%;
        margin-top: 8px;

        .tip{
            font-size: 14px;
            color: #000;

            .link{
                color: #2770EE;
                cursor: pointer;
            }
        }
    }
}
</style>